package com.loooooo.pm2024.modules.search;


import monad.mmseg.analysis.MMSegAnalyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.*;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.*;
import org.apache.lucene.store.FSDirectory;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Paths;

public class DemoIndexer3 {

    static MMSegAnalyzer analyzer = new MMSegAnalyzer();

    public static void main(String[] args) throws IOException {
        String indexPath = "/data/card/search/index";
        index(indexPath);
        long startAt = System.currentTimeMillis();
        search(indexPath, "天涯路");
        long endAt = System.currentTimeMillis();
        System.out.println(endAt - startAt);
    }

    private static void index(String indexFolder) throws IOException {
        File dir = new File(indexFolder);
        if (!dir.exists()) dir.mkdirs();

        //Creating an Lucene IndexWriter
        IndexWriterConfig conf = new IndexWriterConfig(analyzer);
        IndexWriter iw = new IndexWriter(FSDirectory.open(Paths.get(indexFolder)), conf);
        //Iterating through images building the low level features

        String[] strings = {"湖南省长沙市岳麓区麓谷街道保利麓谷林语小区A12-1605",
                "湖南省长沙市岳麓区麓谷街道保利麓谷林语小区A12-1605",
                "湖南省岳阳市岳麓区麓谷街道保利麓谷林语小区A12-1605",
                "海南五指山市天涯路567号-16051",
                "海南五指山市天涯路567号-16052",
                "海南五指山市天涯路567号-16053",
                "海南五指山市天涯路567号-16054",
                "海南五指山市天涯路567号-16055",
                "海南五指山市天涯路567号-16056",
                "海南五指山市天涯路567号-16057",
                "海南五指山市天涯路567号-16058",
                "海南五指山市天涯路567号-16059",
                "海南五指山市天涯路567号-10",
                "海南五指山市天涯路567号-11",
                "海南五指山市天涯路567号-12",
                "海南五指山市天涯路567号-13",
                "海南五指山市天涯路567号-14",
                "海南五指山市天涯路567号-15",
                "湖北长沙市开福区麓谷街道保利麓谷林语小区A12-1605"};

        for (int i = 0; i < strings.length; i++) {
            String text = strings[i];
            Document document = new Document();
            Field idField = new StringField("id", i + "", Field.Store.YES);
            Field subField = new StringField("subject", text, Field.Store.YES);
            Field contentField = new TextField("content", text, Field.Store.YES);
            document.add(idField);
            document.add(subField);
            document.add(contentField);
            //iw.addDocument(document);
            iw.updateDocument(new Term("id", i + ""), document);
        }
        //closing the IndexWriter
        iw.close();
        System.out.println("Finished indexing.");
    }

    public static void search(String indexFolder, String keyword) {
        IndexReader indexReader = null;
        try {
            indexReader = StandardDirectoryReader.open(FSDirectory.open(Paths.get(indexFolder)));
            IndexSearcher searcher = new IndexSearcher(indexReader);
            Term term = new Term("content", keyword);
            //WildcardQuery q = new WildcardQuery(term);
            QueryParser queryParser = new QueryParser("content", analyzer);
            Query q = queryParser.parse(keyword);
            TopDocs topDocs = searcher.search(q, 10);
            System.out.println(topDocs.totalHits);
            ScoreDoc[] scoreDocs = topDocs.scoreDocs;

            QueryScorer scorer = new QueryScorer(q);

            //摘要
            SimpleSpanFragmenter fragmenter = new SimpleSpanFragmenter(scorer);
//关键字样式
            SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter("<b><font color='red'>", "</font></b>");
            //高亮设置
            Highlighter highlighter = new Highlighter(simpleHTMLFormatter, scorer);
            //高亮的范围
            highlighter.setTextFragmenter(fragmenter);

            for (ScoreDoc scoreDoc : scoreDocs) {
                Document document = searcher.doc(scoreDoc.doc);

                String content = document.get("content");
                if (content != null) {
                    TokenStream tokenStream = analyzer.tokenStream("content", new StringReader(content));
                    System.out.println("摘要：" + highlighter.getBestFragment(tokenStream, content));
                }
                System.out.println(scoreDoc.score + "\t\t" + document.get("subject"));
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        } catch (InvalidTokenOffsetsException e) {
            throw new RuntimeException(e);
        }

    }
}
